<template>
  <div class="vote">
    <el-card class="box-card">
      <template #header>
        <h1>{{ title }}</h1>
      </template>
      <div class="sup item">
        <div class="child" :style="{ width: supWidth, background: supBgc }">
          支持人数：{{ supCount }}/{{ supCount + oppCount }}
        </div>
      </div>
      <div class="opp item">
        <div class="child" :style="{ width: oppWidth, background: oppBgc }">
          反对人数：{{ oppCount }}/{{ supCount + oppCount }}
        </div>
      </div>
      <div class="sup item">
        <div class="child" :style="{ width: supWidth, background: supBgc }">
          支持率：{{ supRate }}%
        </div>
      </div>
    </el-card>
    <el-button type="success" :icon="Check" circle @click="support" />
    <el-button type="danger" :icon="Close" circle @click="oppose" />
  </div>
</template>

<script>
import { ref, computed } from "vue";
import { ElButton, ElCard } from "element-plus";
import { Check, Close } from "@element-plus/icons";

export default {
  props: {
    title: {
      type: String,
      required: true,
    },
  },
  components: {
    ElButton,
    ElCard,
  },
  setup() {
    let supCount = ref(0);
    let oppCount = ref(0);
    // 支持方法
    const support = () => {
      supCount.value++; //用ref声明的响应式变量操作时应该用点value的形式
    };
    //反对方法
    const oppose = () => {
      oppCount.value++; //用ref声明的响应式变量操作时应该用点value的形式
    };

    // 计算属性，计算支持率
    const supRate = computed(() => {
      let totalCount = supCount.value + oppCount.value;
      return totalCount === 0
        ? 0
        : ((supCount.value / totalCount) * 100).toFixed(2); // 保留2位小数
    });

    const supWidth = computed(() => {
      let totalCount = supCount.value + oppCount.value;
      return supCount.value === 0
        ? "100%"
        : `${((supCount.value / totalCount) * 100).toFixed(2)}%`; // 保留2位小数
    });
    const oppWidth = computed(() => {
      let totalCount = supCount.value + oppCount.value;
      return oppCount.value === 0
        ? "100%"
        : `${((oppCount.value / totalCount) * 100).toFixed(2)}%`; // 保留2位小数
    });
    const supBgc = computed(() => {
      return oppCount.value === 0 ? "" : "#67c23a";
    });
    const oppBgc = computed(() => {
      return oppCount.value === 0 ? "" : "#f56c6c";
    });
    //将所有成员暴露出去供模板使用
    return {
      supCount,
      oppCount,
      supRate,
      support,
      oppose,
      Check, //图标作为响应式属性需这里暴露出去
      Close, //图标作为响应式属性需这里暴露出去
      supWidth,
      oppWidth,
      supBgc,
      oppBgc,
    };
  },
};
</script>

<style lang='less'>
.vote {
  width: 100%;
  & .item {
    margin-bottom: 5px;
  }
}

.child {
  width: 100%;
  border-radius: 5px;
}

.sup {
  width: 100%;
  border: 1px solid #67c23a;
  border-radius: 5px;
  padding: 2px;
}
.opp {
  width: 100%;
  border: 1px solid #f56c6c;
  border-radius: 5px;
  padding: 2px;
}
</style>